package com.melodyframe.stage.demo.initializer;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.context.ApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import com.melodyframe.stage.core.Stage;
import com.melodyframe.stage.web.StageDispatchFilter;

public class ApplicationInitializer implements WebApplicationInitializer {
	private static ServletContext		servletContext;
	private static ApplicationContext	applicationContext;

	@Override
	public void onStartup(ServletContext sContent) throws ServletException {
		servletContext = sContent;
		initApplicationContent();
		initStage();
		System.out.println("======== init application success! ========");
	}

	public static void initApplicationContent() {
		AnnotationConfigWebApplicationContext aContext = new AnnotationConfigWebApplicationContext();
		aContext.scan("com.melodyframe.stage.demo.initializer",
				"com.melodyframe.stage.demo.service");
		aContext.refresh();
		ContextLoaderListener contextLoaderListener = new ContextLoaderListener(
				aContext);
		servletContext.addListener(contextLoaderListener);
		applicationContext = aContext;
	}

	public static void initStage() {
		StageDispatchFilter stageDispatchFilter = new StageDispatchFilter();
		Stage stage = (Stage) applicationContext.getBean("stage");
		stageDispatchFilter.setStage(stage);
		FilterRegistration characterEncodingFilterRegistration = servletContext
				.addFilter("stageDispatchFilter", stageDispatchFilter);
		characterEncodingFilterRegistration.addMappingForUrlPatterns(null,
				true, "/*");
	}
}
